package com.shiguiwu.springmybatis.spring.property.refresh;



import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @description: 自定义作用域
 * @author: stone
 * @date: Created by 2021/4/6 20:01
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.spring.property
 */
public class BeanRefreshScope implements Scope {
   // @1：定义了一个常量，作为作用域的值
    public static final String SCOPE_NAME = "refresh";

    private final static BeanRefreshScope INSTANCE = new BeanRefreshScope();

    private ConcurrentHashMap<String, Object> beanMap = new ConcurrentHashMap<>();

    private BeanRefreshScope() {

    }

    public static BeanRefreshScope getInstance() {
        return INSTANCE;
    }

    /**
     * 清理当前的bean
     */

    public void clear() {
        INSTANCE.beanMap.clear();

    }



    /**
     * @2这个get方法是关键，自定义作用域会自动调用这个get方法来创建bean对象，这个地方输了一行日志，为了一会方便看效果
     * @param name
     * @param objectFactory
     * @return
     */
    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        //@3：通过objectFactory.getObject()获取bean实例返回

        return this.beanMap.computeIfAbsent(name, k -> objectFactory.getObject());
    }

    @Override
    public Object remove(String name) {
        return null;
    }

    @Override
    public void registerDestructionCallback(String name, Runnable callback) {

    }

    @Override
    public Object resolveContextualObject(String key) {
        return null;
    }

    @Override
    public String getConversationId() {
        return null;
    }
}
